import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { message } from 'ant-design-vue'
import type { IApiResponse } from '@/types/api'

// 创建 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL, // 统一使用 /api 前缀
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 从 localStorage 直接获取 token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse<IApiResponse>) => {
    const { code, message, data } = response.data
    if (code === 200) {
      return data // 直接返回 data，不返回整个 response
    }
    console.log("message",message)
    return Promise.reject(new Error(message || '请求失败'))
  },
  (error) => {
    console.log('网络错误', error)
    return Promise.reject(error)
  }
)

// 请求配置类型
export interface RequestOptions {
  url: string
  method: 'get' | 'post' | 'put' | 'delete'
  params?: Record<string, any>
  data?: any
  headers?: Record<string, string>
  responseType?: 'blob' | 'json' | 'text' | 'arraybuffer'
}

// 请求函数类型
export type RequestFunction = <T = any>(options: RequestOptions) => Promise<T>

const request: RequestFunction = async (options) => {
  return service(options) as unknown as Promise<T>
}

export default request 